﻿using System;
using System.Collections.Generic;
using System.Linq;
using SlimDX.XInput;
using WiimoteLib;

namespace GamepadDriver
{
    public static class WiimoteFactory
    {
        private static List<EventWrappedWiimote> _wiimotes;

        public static void Initialize()
        {
            var wm = new WiimoteCollection();

            try
            {
                wm.FindAllWiimotes();
            }
            catch (WiimoteNotFoundException ex)
            {
                Console.WriteLine("Wiimote not found error: {0}", ex.Message);
            }
            catch (WiimoteException ex)
            {
                Console.WriteLine("Wiimote error: {0}", ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unknown error: {0}", ex.Message);
            }

            _wiimotes = new List<EventWrappedWiimote>();
            for (int index = 0; index < wm.Count; index++)
            {
                _wiimotes.Add(new EventWrappedWiimote(wm[index], (SlimDX.XInput.UserIndex)index));
            }
        }

        public static void Destroy()
        {
            foreach (var wiimote in _wiimotes)
            {
                wiimote.Dispose();
            }
        }

        public static EventWrappedWiimote GetWiimote(UserIndex index)
        {
            return _wiimotes.Where(x => x.UserIndex == index).Single();
        }
    }
}